# FindRivsInference.cmake
# Usage: find_package(RivsInference REQUIRED)
# Provides:
#   RivsInference_FOUND
#   RivsInference_INCLUDE_DIRS
#   RivsInference_LIBRARIES (Inference + RT)
#   Imported targets: Rivs::Inference, Rivs::RT

# Default RIVS_ROOT (if not provided)
if(NOT RIVS_ROOT)
  if(DEFINED ENV{RIVS_ROOT} AND NOT "$ENV{RIVS_ROOT}" STREQUAL "")
    set(RIVS_ROOT "$ENV{RIVS_ROOT}" CACHE PATH "Root prefix of Rivs installation" FORCE)
  else()
    set(RIVS_ROOT "/opt/rivs" CACHE PATH "Root prefix of Rivs installation" FORCE)
  endif()
endif()
message(STATUS "[FindRivsInference] RIVS_ROOT=${RIVS_ROOT}")

set(_RIVS_HINT_PREFIXES
    ${RIVS_ROOT}
    $ENV{RIVS_ROOT}
    $ENV{HOME}/yuan/enrigin_sdk
)

# Search include dir containing RivsInference/RivsInferRuntime.h
set(_RIVSINF_INCLUDE_HINTS)
foreach(pfx IN LISTS _RIVS_HINT_PREFIXES)
  if(pfx)
    list(APPEND _RIVSINF_INCLUDE_HINTS
      ${pfx}/include
      ${pfx}/usr/include
      ${pfx}/opt/rivs/include
    )
  endif()
endforeach()

find_path(RivsInference_INCLUDE_DIR
  NAMES RivsInference/RivsInferRuntime.h rivs/rivs_ext.h
  HINTS ${_RIVSINF_INCLUDE_HINTS}
  PATHS /usr/include /usr/local/include /opt/rivs/include
)

# Search libs
set(_RIVSINF_LIB_HINTS)
foreach(pfx IN LISTS _RIVS_HINT_PREFIXES)
  if(pfx)
    list(APPEND _RIVSINF_LIB_HINTS
      ${pfx}/lib
      ${pfx}/usr/lib
      ${pfx}/opt/rivs/lib
    )
  endif()
endforeach()

find_library(RivsInference_LIBRARY
  NAMES RivsInference
  HINTS ${_RIVSINF_LIB_HINTS}
  PATHS /usr/lib /usr/local/lib /opt/rivs/lib
)

find_library(RivsRT_LIBRARY
  NAMES rivsrt
  HINTS ${_RIVSINF_LIB_HINTS}
  PATHS /usr/lib /usr/local/lib /opt/rivs/lib
)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(RivsInference
  REQUIRED_VARS RivsInference_INCLUDE_DIR RivsInference_LIBRARY RivsRT_LIBRARY
)

if(RivsInference_FOUND)
  set(RivsInference_INCLUDE_DIRS ${RivsInference_INCLUDE_DIR})
  set(RivsInference_LIBRARIES ${RivsInference_LIBRARY} ${RivsRT_LIBRARY})
  message(STATUS "[FindRivsInference] Include dir: ${RivsInference_INCLUDE_DIR}")
  message(STATUS "[FindRivsInference] Inference lib: ${RivsInference_LIBRARY}")
  message(STATUS "[FindRivsInference] RT lib: ${RivsRT_LIBRARY}")

  if(NOT TARGET Rivs::Inference)
    add_library(Rivs::Inference UNKNOWN IMPORTED)
    set_target_properties(Rivs::Inference PROPERTIES
      IMPORTED_LOCATION "${RivsInference_LIBRARY}"
      INTERFACE_INCLUDE_DIRECTORIES "${RivsInference_INCLUDE_DIRS}"
    )
  endif()

  if(NOT TARGET Rivs::RT)
    add_library(Rivs::RT UNKNOWN IMPORTED)
    set_target_properties(Rivs::RT PROPERTIES
      IMPORTED_LOCATION "${RivsRT_LIBRARY}"
      INTERFACE_INCLUDE_DIRECTORIES "${RivsInference_INCLUDE_DIRS}"
    )
  endif()
endif()
